/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');
var async = require('async');

// Schema 结构
var ItbTradeOrderDetailModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`detail_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '订单明细id',
  //`detail_no` varchar(50) NOT NULL DEFAULT '' COMMENT 'itb自定义子订单号',
  //`order_id` bigint(20) NOT NULL COMMENT '订单id',
  //`state` int(3) NOT NULL DEFAULT '0' COMMENT '订单明细状态: 保留,暂未使用',
  //`item_id` bigint(20) NOT NULL COMMENT '商品id',
  //`pp_id` bigint(20) NOT NULL COMMENT '印刷参数（套餐）',
  //`unit` varchar(20) NOT NULL COMMENT '计量单位',
  //`qty` bigint(20) NOT NULL COMMENT '数量',
  //`user_doc_id` bigint(20) NOT NULL COMMENT '用户作品id',
  //`fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '总项：订单明细金额（单位为rmb分）',
  //`product_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '子项：印刷费（单位为rmb分）',
  //`design_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '子项：设计费（单位为rmb分）',
  //`mail_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '子项：快递费（单位为rmb分）',
  //`desc` varchar(200) DEFAULT '' COMMENT '订单描述',
  //`express` varchar(100) NOT NULL COMMENT '快递公司',
  //`tracking_no` varchar(100) NOT NULL COMMENT '快递单号',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL,
  //`del_flg` int(1) NOT NULL DEFAULT '0',


};
ItbTradeOrderDetailModel.prototype = new ItbBaseModel();

// 取得表名
ItbTradeOrderDetailModel.prototype.getTableName = function(){
    return 'itb_trade_order_detail';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbTradeOrderDetailModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'detail_id='+this.detail_id;
}

function sql_delAccessory(userId, orderId){
    var sql = " UPDATE itb_trade_order_detail t, itb_trade_order o, itb_items i, tg_type p "+
        " SET t.del_flg=1, t.update_time=sysdate() "+
        "     ,t.update_by="+userId+
        " WHERE o.order_id="+orderId+" AND o.user_id="+userId+" AND o.del_flg=0 "+
        " AND t.order_id=o.order_id AND t.del_flg=0 "+
        " AND i.item_id=t.item_id AND i.del_flg=0 "+
        " AND p.type_id=i.type_id AND p.top_parent=5 AND p.del_flg=0 ";
    return sql;
}

//------------------------------------------------------------------
// 删除[配件]子订单
// 参数 userId: 用户id
// 参数 orderId: 商品订单id
ItbTradeOrderDetailModel.prototype.delAccessory = function(userId, orderId, callback) {
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.delAccessory Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql = sql_delAccessory(userId, orderId);

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            callback(error, result);
        });
    });
};

//------------------------------------------------------------------
// 绑定套餐至商品订单: (绑定pp_id到指定订单的[印品]子订单，同时删除存在的[配件]子订单)
// 参数 userId: 用户id
// 参数 orderId: 商品订单id
ItbTradeOrderDetailModel.prototype.bindPrintParamId = function(userId, orderId, ppId, callback) {
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.bindPrintParamId Err:'+err);
        }

        var trans = connection.beginTransaction(function(error){
            if (error) {
                // And done with the connection.
                connection.release();
                return callback(error,null)
            }else{
                var asynFuncs = [
                    function(callback1){
                        // 更新印品子订单
                        var sql = " UPDATE itb_trade_order_detail t, itb_trade_order o, itb_items i, tg_type p "+
                            " SET t.pp_id="+ppId+
                            " 	  ,t.update_time=sysdate() "+
                            "     ,t.update_by="+userId+
                            " WHERE o.order_id="+orderId+" AND o.user_id="+userId+" AND o.del_flg=0 "+
                            " AND t.order_id=o.order_id AND t.del_flg=0 "+
                            " AND i.item_id=t.item_id AND i.design_id is not null AND i.del_flg=0 "+
                            " AND p.type_id=i.type_id AND p.top_parent=4 AND p.del_flg=0 ";

                        connection.query(sql,function(error,info){
                            callback1(error,info);
                        });
                    },
                    function(callback2){
                        // 更新配件子订单
                        var sql = sql_delAccessory(userId, orderId);

                        connection.query(sql,function(error,info){
                            callback2(error,info);
                        });
                    }
                ];
                async.series(asynFuncs,function(error,results){
                    if (error) {
                        connection.rollback();

                        // And done with the connection.
                        connection.release();
                        return callback(error, null)

                    } else {
                        // 没有错误 提交事务
                        connection.commit(function(error, info) {
                            // And done with the connection.
                            connection.release();

                            if(error){
                                return callback(error, null);
                            }else{
                                return callback(null, null);
                            }
                        });
                    }
                });
            }
        });
    });
};

//------------------------------------------------------------------
// 更新订单配件数量: 更新[配件]子订单
// 参数 userId: 用户id
// 参数 orderId: 商品订单id
// 参数 AccessoryCnt: 配件数量
ItbTradeOrderDetailModel.prototype.modifyAccessoryCnt = function(userId, orderId, AccessoryCnt, callback) {
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.modifyAccessoryCnt Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql = " UPDATE itb_trade_order_detail t, itb_trade_order o, itb_items i, tg_type p "+
            " SET t.qty="+Number(AccessoryCnt||'0')+
            "     ,t.update_time=sysdate() "+
            "     ,t.update_by="+userId+
            " WHERE o.order_id="+orderId+" AND o.user_id="+userId+" AND o.del_flg=0 "+
            " AND t.order_id=o.order_id AND t.del_flg=0 "+
            " AND i.item_id=t.item_id AND i.del_flg=0 "+
            " AND p.type_id=i.type_id AND p.top_parent=5 AND p.del_flg=0 ";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            callback(error, result);
        });
    });
};

//------------------------------------------------------------------
/* 获取订单产品信息
 * 参数: id	 订单id
 * 参数： callback：回调，参数如下：
 *          error:错误消息
 *          data:如下结构：
 *          [{
 * 	            "id":345,                           // 作品id
 * 	            "thumb":"http://oss-image.jpg",     // 作品图片
 * 	            "qty":2,                            // 作品的数量
 * 	            "productFee":200,                   // 作品的印刷费
 * 	            "designFee":200,                    // 作品的印刷费
 * 	            "mailFee":200,                      // 作品的印刷费
 * 	            "title":"商品名",            // 商品名称
 * 	            "desc":"300G白卡 亚模",      // 商品描述
 * 	            "price":100,                // 商品最低价
 * 	            "priceCount":2,             // 商品最低价对应数量
 * 	            "size":"A4大小(45x64)",     // 商品描述
 * 	            "unit":"张",                // 商品单位
 * 	            "printParaId":989,          // 商品的印刷参数id
 * 	            "detailOrderId":1,          // 商品子订单的id
 *          }]
 */
ItbTradeOrderDetailModel.prototype.getPrintProductInfo = function(orderId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getPrintProductInfo Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            " SELECT t1.*, "+
            "        CASE WHEN up.thumb IS NOT NULL THEN concat(up.thumb,'?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5') "+
            "        WHEN t1.item_thumb IS NOT NULL THEN concat(t1.item_thumb,'?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5') "+
            "        ELSE '' END AS thumb "+
            " FROM "+
            "   (SELECT d.detail_id AS detailOrderId, "+
            "           d.user_doc_id AS id, "+
            "           d.fee AS fee, "+
            "           d.product_fee AS productFee, "+
            "           d.design_fee AS designFee, "+
            "           d.mail_fee AS mailFee, "+
            "           d.qty AS qty, "+
            "           d.pp_id AS printParaId, "+
            "          d.express AS express, " +
            "          d.tracking_no AS tracking_no," +
            "           i.item_name AS title, "+
            "           func_parse_string_array(i.thumbs,0) as item_thumb, "+
            "           i.desc AS `desc`, "+
            "           concat(s.print_w,'x',s.print_h) AS size, "+
            "        qp.show AS priceCount, "+// 商品最低价对应数量
            "        qp.price AS price, "+// 商品最低价
            "        qp.unit AS unit "+
            "    FROM itb_trade_order_detail d, "+
            "         itb_items i, "+
            "         itb_print_param p, itb_qty_price qp, "+
            "         (SELECT qp2.pp_id, min(qp2.min) as valmin FROM itb_qty_price qp2 WHERE qp2.del_flg=0 group by qp2.pp_id) qp3, "+
            "         tg_size s "+
            "    WHERE d.`order_id`= "+ orderId+
            "      AND d.del_flg=0 "+
            "      AND d.item_id=i.`item_id` "+
            "      AND i.del_flg=0 "+
            "      AND d.pp_id = p.pp_id "+
            //"      AND p.del_flg=0 "+//套餐可能下架 del by xc 2018-03-19
            "      AND qp.del_flg=0 AND qp.pp_id=p.pp_id "+
            "      AND qp.pp_id=qp3.pp_id and qp.min=qp3.valmin "+// 关联qp3取最小价格
            "      AND p.size_id = s.size_id "+
            "      AND s.del_flg=0 ) t1 "+
            " LEFT JOIN tg_user_page up ON up.del_flg=0 AND up.doc_id=t1.id AND up.page_index=0 ";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            callback(error, result);
        });
    });
}

/**
 * ##### 获取子订单信息 #####
 *
 * 返回值1 (按照组合商品分组):
 * [
 *  {
 *      detail_id: 1,
 *      base_detail_id: null,
 *      item_id: 123,           // 主商品
 *      ...
 *      totalProductFee: 300,   // 组合商品的总制作费
 *      totalDesignFee: 200,    // 组合商品的总设计费
 *      totalMailFee: 100,      // 组合商品的总邮费
 *      assyList: [],           // 配件商品
 *  }
 * ]
 *
 * 返回值2 (按照组合商品分组的基础上,按合作方分组):
 * [
 *  {
 *      pId: 123,               // 合作方id
 *      totalProductFee: 300,   // 该合作方分组内所有商品的总制作费
 *      totalDesignFee: 200,    // 该合作方分组内所有商品的总设计费
 *      totalMailFee: 100,      // 该合作方分组内所有商品的总邮费
 *      itemList: [],           // 同(返回值1)的结构
 *  }
 * ]
 */
ItbTradeOrderDetailModel.prototype.getPrintProductInfo_v5_5 = function(orderId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getPrintProductInfo_v5_5 Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            " SELECT t1.*, "+
            "        CASE WHEN up.thumb IS NOT NULL THEN concat(up.thumb,'?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5') "+
            "        WHEN t1.item_thumb IS NOT NULL THEN concat(t1.item_thumb,'?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5') "+
            "        ELSE '' END AS thumb "+
            " FROM "+
            "   (SELECT d.detail_id, "+
            "           d.base_detail_id, "+
            "           CASE WHEN d.base_detail_id>0 THEN 1 ELSE 0 END AS isAssyFlg, "+
            "           CASE WHEN d.base_detail_id>0 THEN d.base_detail_id ELSE detail_id END AS main_detail_id, "+
            "           IFNULL(d.partner_id,0) AS partner_id, "+// 合作方:印刷厂
            "           d.item_id, "+
            "           d.user_doc_id, "+
            "           IFNULL(d.fee,0) AS fee, "+
            "           IFNULL(d.product_fee,0) AS product_fee, "+
            "           IFNULL(d.design_fee,0) AS design_fee, "+
            "           IFNULL(d.mail_fee,0) AS mail_fee, "+
            "           IFNULL(d.qty,0) AS qty, "+
            "           d.unit, "+
            "           d.pp_id, "+
            "           d.express, " +
            "           d.tracking_no," +
            "           i.item_name, "+
            "           func_parse_string_array(i.thumbs,0) as item_thumb, "+
            "           i.desc AS item_desc, "+
            "           p.pp_name, p.desc AS pp_desc, p.pricing, "+
            "           qp.unit AS qty_unit, qp.min AS qty_min, qp.max AS qty_max, qp.show AS qty_show, qp.price AS qty_price, "+
            "           concat(s.print_w,'x',s.print_h) AS size "+
            "    FROM itb_trade_order_detail d, "+
            "         itb_items i, "+
            "         itb_print_param p, itb_qty_price qp, "+
            "         tg_size s "+
            "    WHERE d.`order_id`= "+ orderId+
            "      AND d.del_flg=0 "+
            "      AND d.item_id=i.`item_id` "+
            //"      AND i.del_flg=0 "+ // 由于商品有可能下架但是用户之前可能有过购买记录, 故不要求该笔订单的商品必须还在, remove by wangjun 2017-09-13
            "      AND d.pp_id = p.pp_id "+
            //"      AND p.del_flg=0 "+// 套餐可能下架 del by xc 2018-02-26
            "      AND qp.del_flg=0 AND qp.pp_id=p.pp_id "+
            "      AND ( (p.pricing=20 AND qp.min=1) OR (p.pricing=10 AND qp.min<=d.qty AND qp.max>=d.qty) ) "+
            "      AND p.size_id = s.size_id "+
            "      AND s.del_flg=0 ) t1 "+
            " LEFT JOIN tg_user_page up ON up.del_flg=0 AND up.doc_id=t1.user_doc_id AND up.page_index=0 "+
            // 先按印刷厂排序，再将组合商品的主商品和配件排在一起
            " ORDER BY t1.partner_id, t1.main_detail_id, t1.isAssyFlg, t1.detail_id ";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            var retInfo = [];
            // 按组合商品分组
            if(result && result.length>0) {
                // 兼容老数据(配件没有base_detail_id)
                if( result.length==2 &&
                    (Number(result[0].user_doc_id||'0')==0 || Number(result[1].user_doc_id||'0')==0) ) {// 存在配件

                    if(Number(result[1].user_doc_id||'0')==0){
                        var tmpItem = result[0];
                        tmpItem.assyList = [result[1]];
                        tmpItem.totalProductFee = result[0].product_fee + result[1].product_fee;
                        tmpItem.totalDesignFee = result[0].design_fee + result[1].design_fee;
                        tmpItem.totalMailFee = result[0].mail_fee + result[1].mail_fee;
                        retInfo.push(tmpItem);
                    } else {
                        var tmpItem = result[1];
                        tmpItem.assyList = [result[0]];
                        tmpItem.totalProductFee = result[0].product_fee + result[1].product_fee;
                        tmpItem.totalDesignFee = result[0].design_fee + result[1].design_fee;
                        tmpItem.totalMailFee = result[0].mail_fee + result[1].mail_fee;
                        retInfo.push(tmpItem);
                    }

                } else {
                    // 按照main_detail_id分组
                    var tmpItem = null;
                    var tmpAssy=new Array();

                    for(var i=0; i<result.length; i++) {
                        if(i==0) {
                            tmpItem = result[0];
                            tmpItem.totalProductFee = result[0].product_fee;
                            tmpItem.totalDesignFee = result[0].design_fee;
                            tmpItem.totalMailFee = result[0].mail_fee;
                        }

                        if(result[i].main_detail_id != tmpItem.main_detail_id) {
                            tmpItem.assyList = tmpAssy;
                            retInfo.push(tmpItem);

                            tmpItem = result[i];
                            tmpItem.totalProductFee = result[i].product_fee;
                            tmpItem.totalDesignFee = result[i].design_fee;
                            tmpItem.totalMailFee = result[i].mail_fee;
                            tmpAssy = new Array();
                        }

                        if(result[i].base_detail_id>0) {
                            tmpAssy.push(result[i]);
                            tmpItem.totalProductFee += result[i].product_fee;
                            tmpItem.totalDesignFee += result[i].design_fee;
                            tmpItem.totalMailFee += result[i].mail_fee;
                        }

                        if(i==result.length-1){// 最后一条
                            tmpItem.assyList = tmpAssy;
                            retInfo.push(tmpItem);
                        }
                    }
                }
            }

            if(THIS.GroupByPartner == 1) {
                // 在组合商品的基础上，再按印刷厂分组
                var retInfo2 = [];
                if(retInfo && retInfo.length>0) {

                    var tmpId = retInfo[0].partner_id;
                    var tmpItems=new Array();

                    var tmpTotalProductFee = 0;
                    var tmpTotalDesignFee = 0;
                    var tmpTotalMailFee = 0;

                    for(var i=0; i<retInfo.length; i++) {
                        if(retInfo[i].partner_id != tmpId) {
                            retInfo2.push({
                                pId: tmpId,
                                totalProductFee: tmpTotalProductFee,
                                totalDesignFee: tmpTotalDesignFee,
                                totalMailFee: tmpTotalMailFee,
                                itemList:tmpItems
                            });

                            tmpId = result[i].partner_id;
                            tmpItems = new Array();

                            tmpTotalProductFee = 0;
                            tmpTotalDesignFee = 0;
                            tmpTotalMailFee = 0;
                        }

                        tmpItems.push(retInfo[i]);
                        tmpTotalProductFee += retInfo[i].totalProductFee;
                        tmpTotalDesignFee += retInfo[i].totalDesignFee;
                        tmpTotalMailFee += retInfo[i].totalMailFee;

                        if(i==retInfo.length-1){// 最后一条
                            retInfo2.push({
                                pId: tmpId,
                                totalProductFee: tmpTotalProductFee,
                                totalDesignFee: tmpTotalDesignFee,
                                totalMailFee: tmpTotalMailFee,
                                itemList:tmpItems
                            });
                        }
                    }
                }
                return callback(error, retInfo2);

            } else {
                // 按组合商品分组返回
                return callback(error, retInfo);
            }
        });
    });
};

/* 获取订单的第一个子订单的信息
 * 参数: id	 订单id
 * 参数： callback：回调，参数如下：
 *          error:错误消息
 *          info:对象，含有以下属性：
 *                  prov:省id
 *                  city:市id
 *                  weight:重量，单位KG
 *                  mail_fee:子订单纪录的邮费
 *                  detail_id: 子订单id
 */
ItbTradeOrderDetailModel.prototype.getFirstAddressAndWeight = function(id, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getFirstAddressAndWeight Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            " SELECT m1.*, "+
            "        m2.* "+
            " FROM "+
            "  "+
            "   (SELECT d.detail_id, "+
            "           d.qty, "+
            "           d.pp_id, "+
            "           d.mail_fee, "+
            "           qp.weight, "+
            "           d.order_id "+
            "    FROM itb_trade_order_detail d, "+
            "         itb_qty_price qp "+
            "    WHERE d.`order_id`= "+id+
            "    AND d.`del_flg`=0 "+
            "    AND qp.del_flg=0 "+
            "    AND qp.pp_id = d.pp_id "+
            "    AND qp.show = d.qty  "+
            "    LIMIT 0,1) m1, "+
            "     "+
            "   (SELECT a.prov, "+
            "           a.city, "+
            "           t.order_id "+
            "    FROM itb_trade_order t, "+
            "         itb_address a "+
            "    WHERE t.del_flg=0 "+
            "    AND t.`order_id`= "+id+
            "    AND t.del_flg=0 "+
            "    AND t.addr_id=a.addr_id  "+
            "    LIMIT 0,1) m2 "+
            "     "+
            " WHERE m1.order_id = m2.order_id ";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();


            if(result && result.length>0){
                return callback(error, result[0]);
            }else{
                return callback(error, null);
            }
        });
    });
}
//------------------------------------------------------------------
/* 更新子订单的邮费，以及订单的总金额
 * 参数: orderId	 订单id
 * 参数: detailOrderId	 子订单id
 * 参数: t    邮费金额变化量
 * 参数： callback：回调，参数如下：
 *          error:错误消息
 *          orderId:订单id，失败返回null
 * 注意：使用事务处理改更新，错误后回滚
 */
ItbTradeOrderDetailModel.prototype.updateMailFeeOfOrder = function(orderId, detailOrderId, t, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.updateMailFeeOfOrder Err:'+err);
            return callback(err,null);
        }

        var trans = connection.beginTransaction(function(error){
            if (error) {
                // And done with the connection.
                connection.release();
                return callback(error,null)
            }else{
                var asynFuncs = [
                    function(callback1){
                        var sql =
                            " update itb_trade_order_detail  "+
                            " set   mail_fee=mail_fee+"+t+", "+
                            " 	    fee=fee+"+t+
                            " where detail_id="+detailOrderId;
                        connection.query(sql,function(error,info){
                            callback1(error,info);
                        });
                    },
                    function(callback2){
                        var sql =
                            " update itb_trade_order  "+
                            " set total_fee=total_fee+"+t+" "+
                            " where order_id="+orderId;
                        connection.query(sql,function(error,info){
                            callback2(error,info);
                        });
                    }
                ];
                async.series(asynFuncs,function(error,results){
                    if (error) {
                        connection.rollback();

                        // And done with the connection.
                        connection.release();
                        return callback(error,null)

                    } else {
                        // 没有错误 提交事务
                        connection.commit(function(error, info) {
                            // And done with the connection.
                            connection.release();

                            if(error){
                                return callback(error, null)
                            }else{
                                return callback(null,orderId)
                            }
                        });
                    }
                });
            }
        });


    });
}

//------------------------------------------------------------------
/* 更新子订单的数量、金额，以及订单的总金额
 * 参数: orderId	 订单id
 * 参数: detailOrderId	 子订单id
 * 参数: count	 数量
 * 参数: t       金额变化量
 * 参数： callback：回调，参数如下：
 *          error:错误消息
 *          orderId:订单id，失败返回null
 * 注意：使用事务处理改更新，错误后回滚
 */
ItbTradeOrderDetailModel.prototype.updateProductFeeOfOrder = function(orderId, detailOrderId, count,t, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.updateProductFeeOfOrder Err:'+err);
            return callback(err,null);
        }

        var trans = connection.beginTransaction(function(error){
            if (error) {
                // And done with the connection.
                connection.release();
                return callback(error,null)
            }else{
                var asynFuncs = [
                    function(callback1){
                        var sql =
                            " update itb_trade_order_detail  "+
                            " set   qty = "+count+", "+
                            " 	    product_fee=product_fee+"+t+", "+
                            " 	    fee=fee+"+t+
                            " where detail_id="+detailOrderId;

                        connection.query(sql,function(error,info){
                            callback1(error,info);
                        });
                    },
                    function(callback2){
                        var sql =
                            " update itb_trade_order  "+
                            " set total_fee=total_fee+"+t+" "+
                            " where order_id="+orderId;
                        connection.query(sql,function(error,info){
                            callback2(error,info);
                        });
                    }
                ];
                async.series(asynFuncs,function(error,results){
                    if (error) {
                        connection.rollback();

                        // And done with the connection.
                        connection.release();
                        return callback(error,null)

                    } else {
                        // 没有错误 提交事务
                        connection.commit(function(error, info) {
                            // And done with the connection.
                            connection.release();

                            if(error){
                                return callback(error, null)
                            }else{
                                return callback(null,orderId)
                            }
                        });
                    }
                });
            }
        });


    });
}
//------------------------------------------------------------------
/* 取得数量对应的价格
 * 参数: detailOrderId	 订单id
 * 参数: count	 数量
 * 参数： callback：回调，参数如下：
 *          error:错误消息
 *          price:价格，失败返回null
 */
ItbTradeOrderDetailModel.prototype.getPriceOfCount = function(detailOrderId, count, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getPriceOfCount Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            " select qp.* "+
            " from itb_trade_order_detail od, "+
            " 	itb_qty_price qp "+
            " where od.detail_id="+detailOrderId+
            " and od.del_flg=0 "+
            " and qp.pp_id = od.pp_id "+
            " and ("+count+">=qp.min and qp.max>="+count+")"+
            " and qp.del_flg=0";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            if(error){
                return callback(error, null);
            }
            if(!result || result.length==0){
                return callback(null,null);
            }

            return callback(null, result[0].price);
        });
    });
}

//todo 新增接口, 待审核 begin
//---------------------------------------获取子订单信息(仿照getPrintProductInfo)----------------------------------------------
/**
 * 获取订单信息, 印刷商品信息, 配件信息
 *
 * */
ItbTradeOrderDetailModel.prototype.getDetailOrderInfoByOrderId = function(orderId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getDetailOrderInfoByOrderId Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            "SELECT x.*, " +
            "       CASE " +
            "           WHEN up.thumb IS NOT NULL THEN concat(up.`thumb`, '?x-oss-process=image/resize,m_pad,h_400,w_400,color_f5f5f5') " +
            "           ELSE '' " +
            "       END AS thumb " +
            "FROM " +
            "  (SELECT t1.*, " +
            "          t2.show AS priceCount, " +
            "          t2.price AS price, " +
            "          t2.unit AS unit, " +
            "          MIN(t2.min), " +
            "          IF(5=t1.item_type, 1, 0) AS isAccesstory " +
            "   FROM " +
            "     (SELECT d.detail_id AS detailOrderId, " +
            "             d.user_doc_id AS id, " +
            "             d.fee AS fee, " +
            "             d.product_fee AS productFee, " +
            "             d.design_fee AS designFee, " +
            "             d.mail_fee AS mailFee, " +
            "             d.qty AS qty, " +
            "             d.pp_id AS printParaId, " +
            "             i.item_name AS title, " +
            "             i.desc AS `desc`, " +
            "             i.item_id as item_id," +
            "             concat(s.print_w, 'x', s.print_h) AS size, " +
            "             t.top_parent AS item_type, " +
            "             p.pp_name AS printParamName " +
            "      FROM itb_trade_order_detail d, " +
            "           itb_items i, " +
            "           itb_print_param p, " +
            "           tg_size s, " +
            "           tg_type t " +
            "      WHERE d.`order_id` = " + orderId +
            "        AND d.del_flg = 0 " +
            "        AND d.item_id = i.`item_id` " +
            "        AND i.del_flg = 0 " +
            "        AND d.pp_id = p.pp_id " +
            "        AND p.del_flg = 0 " +
            "        AND p.size_id = s.size_id " +
            "        AND s.del_flg = 0 " +
            "        AND t.type_id = i.type_id) t1, " +
            "                                   itb_qty_price t2 " +
            "   WHERE t1.printParaId = t2.pp_id " +
            "     AND t2.del_flg = 0 " +
            "   GROUP BY t1.detailOrderId) x " +
            "LEFT JOIN tg_user_page up ON x.id = up.doc_id " +
            "AND up.page_index = 0 " +
            "AND up.del_flg = 0 ";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            callback(error, result);
        });
    });
}
// todo 新增接口 待审核 end

//------------------------------------------------------------------
/* 取得订单中 印刷商品 的子订单
 * 参数: orderId	 订单id
 * 参数： callback：回调，参数如下：
 *          error:错误消息
 *          data:对象，属性如下：
 *          {
 *              detail_id:917
 *              pp_id:202
 *              type_id:40301
 *              size_id:6
 *          }
 */
ItbTradeOrderDetailModel.prototype.getDetailOrderOfPrint = function(orderId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getDetailOrderOfPrint Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            ' select od.`detail_id`,  '+
            ' 		od.pp_id , '+
            ' 		i.`type_id`, '+
            ' 		p.size_id '+
            ' from itb_trade_order_detail od '+
            ' 	, itb_items i '+
            ' 	, itb_print_param p '+
            ' where od.order_id= '+ orderId +
            ' and od.del_flg=0 '+
            ' and od.user_doc_id is not null '+
            ' and od.item_id=i.`item_id` '+
            ' and od.pp_id=p.pp_id '+
            ' and p.`size_id` '+
            ' limit 0,1 ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            if(error){
                return callback(error, null);
            }
            if(!result || result.length==0){
                return callback(null,null);
            }

            return callback(null, result[0]);
        });
    });
}
//------------------------------------------------------------------
/* 取得订单中 配件商品 的子订单
 * 参数: orderId	 订单id
 * 参数： callback：回调，参数如下：
 *          error:错误消息
 *          data:数组， 数组元素为，ItbQtyPriceModel结构
 */
ItbTradeOrderDetailModel.prototype.getOrderAccessoryCount = function(orderId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getOrderAccessoryCount Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            '  			 select qp.* '+
            '              from itb_trade_order_detail od , '+
            '              	  itb_qty_price	qp '+
            '              where od.order_id=    '+orderId+
            '              and od.del_flg=0  '+
            '              and od.user_doc_id is null  '+
            '              and od.pp_id=qp.pp_id '+
            '              and qp.del_flg=0 ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            if(error){
                return callback(error, null);
            }
            if(!result || result.length==0){
                return callback(null,null);
            }

            return callback(null, result);
        });
    });
}

//------------------------------------------------------------------
// todo 新增接口 待审核 begin
/**
 * 获取订单可以添加配件的列表
 * 参数: type_id 用户作品三级分类 id
 *      callback 回调
 * */
ItbTradeOrderDetailModel.prototype.tradeOrderCanAddAccessories = function(type_id, callback){
    pool.pool.getConnection(function(err, connection){
       if(err) {
           console.log('ItbTradeOrderDetailModel.js [tradeOrderCanAddAccesstory] err' + err);
       }
        var sql = "SELECT func_find_accessory_type("+type_id+") AS accessories";
        console.log(sql);
        connection.query(sql, function(error, result){
            connection.release();

            if(error){
                return callback(error, null);
            }

            if(!result || result.length ==0 ){
                return callback(null, null);
            }
            return callback(null, result[0].accessories);
        });
    });
};
// todo 新增接口 待审核 end

//------------------------------------------------------------------
// 更新vip订单[有效期]信息
// stTime: 有效开始时间
ItbTradeOrderDetailModel.prototype.updVipOdrExpTime = function(dtlId, userId, stTime, callback) {
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.updVipOdrExpTime Err:'+err);
            return callback(err,null);
        }
        // Use the connection

        var sql = " UPDATE itb_trade_order_detail t, itb_trade_order o, itb_items i, tg_type p "+
            " SET t.update_time=sysdate() "+
            " ,t.update_by="+userId+
            " ,t.valid_time='"+stTime+"'"+
            " ,t.expiry_time=date_add('"+stTime+"', INTERVAL t.qty MONTH) "+
            " WHERE t.del_flg=0 AND t.detail_id="+dtlId+
            " AND o.user_id="+userId+" AND o.del_flg=0 AND t.order_id=o.order_id "+
            " AND i.item_id=t.item_id AND i.del_flg=0 "+
            " AND p.type_id=i.type_id AND p.top_parent=9 AND p.del_flg=0 ";

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error) {
                console.log('ItbTradeOrderDetailModel.updVipOdrExpTime error:'+error);
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};


/*
* 查询商品订单类型(实物,虚拟)
*
* @author 王俊
* @date 2018-04-18
*
* @param orderId 订单类型
* @param callback 回调函数
*           err: 查询失败
*           data: {
*               orderType: 10 商品订单, 40, 虚拟商品
*               pp.*
*           }
*
* */
ItbTradeOrderDetailModel.prototype.checkTradeOrderTypeInfo = function (orderId, callback) {

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.checkTradeOrderTypeInfo Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var sql =
            ' SELECT if(ipp.type=3, 40, 10) AS orderType, ' +
            '        ipp.* ' +
            ' FROM itbour.itb_trade_order_detail itod, ' +
            '      itbour.itb_print_param ipp ' +
            ' WHERE itod.del_flg = 0 ' +
            '   AND itod.order_id = ' + orderId +
            '   AND ipp.del_flg = 0 ' +
            '   AND ipp.pp_id = itod.pp_id ';
        console.log(sql);
        connection.query(sql, function(error, results) {
            // And done with the connection.
            connection.release();

            if(error || !results || results.length <=0) {
                console.log('ItbTradeOrderDetailModel.checkTradeOrderTypeInfo error:'+error);
                callback(error, null);
            } else {
                callback(error, results[0]);
            }
        });
    });
};


/**
 * 获取指定订单数组的子订单信息
 *
 * @author 王俊
 *
 *
 * @param orderIds  orderId 的数组
 * @param callback
 *          error:
 *          results: detail 的行数据数组
 */
ItbTradeOrderDetailModel.prototype.getOrdersDetailInfo = function (orderIds, callback) {

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbTradeOrderDetailModel.getOrdersDetailInfo Err:'+err);
            return callback(err,null);
        }
        // Use the connection
        var ids = orderIds.join(',');
        var sql = ' SELECT *' +
            ' FROM itb_trade_order_detail tod' +
            ' WHERE tod.del_flg=0' +
            '   AND tod.order_id IN ('+ids+')';
        console.log(sql);
        connection.query(sql, function(error, results) {
            // And done with the connection.
            connection.release();
            callback(error, results);
        });
    });
};



//------------------------------------------------------------------
// 导出
module.exports = ItbTradeOrderDetailModel;